class IDGenerator {
    private epoch: number;
    private workerIdBits: number;
    private sequenceBits: number;
    private maxWorkerId: number;
    private sequenceMask: number;

    private lastTimestamp: number;
    private sequence: number;
    private workerId: number;

    constructor() {
        this.epoch = 1625097600000; // 设置起始时间戳，这里以毫秒为单位，对应于 UTC 时间 2021-07-01 00:00:00
        this.workerIdBits = 3;     // 总共使用 3 位表示 worker id
        this.sequenceBits = 5;     // 总共使用 5 位表示序列号
        this.maxWorkerId = -1 ^ (-1 << this.workerIdBits);
        this.sequenceMask = -1 ^ (-1 << this.sequenceBits);

        this.lastTimestamp = -1;
        this.sequence = 0;
        this.workerId = 0;
    }

    public generate(): number {
        const currTimestamp = this.getCurrentTimestamp();

        if (currTimestamp < this.lastTimestamp) {
            throw new Error("Clock moved backwards. Refusing to generate id.");
        }

        if (currTimestamp === this.lastTimestamp) {
            this.sequence = (this.sequence + 1) & this.sequenceMask;
            if (this.sequence === 0) {
                return this.waitNextMillisecond(currTimestamp);
            }
        } else {
            this.sequence = 0;
        }

        this.lastTimestamp = currTimestamp;

        let id = (currTimestamp - this.epoch) << (this.workerIdBits + this.sequenceBits);
        id |= (this.workerId << this.sequenceBits);
        id |= this.sequence;
        return parseInt(Math.abs(id).toString().slice(-8));
    }

    private getCurrentTimestamp(): number {
        return new Date().getTime();
    }

    private waitNextMillisecond(lastTimestamp: number): number {
        while (lastTimestamp === this.getCurrentTimestamp()) {
            // 等待下一个毫秒
        }
        return this.getCurrentTimestamp();
    }
}
export {IDGenerator}